#include "mainwindow.h"

#include <QDockWidget>
#include <QMenu>
#include <QMenuBar>
#include <QAction>
#include <QFileDialog>

#include "render.h"
#include "panel.h"

#include "jarvis.h"
#include "vector.h"

#include <cstdlib>

std::vector<Tujchi::Vector> test(void) {
	using namespace Tujchi;
	srand(0);
	std::vector<Vector> points;
	points.push_back(Vector(10.0,-10.0));
	for(int i =0; i < 500; i++) {
		int random = rand()%9;
		int random2 = rand()%9;
		int random3 = rand()%2;
		int random4 = rand()%2;
		if(random3 == 1)
			random2*=-1;
		if(random4 == 1)
			random*=-1;
		points.push_back(Vector(random, random2));
	}
	return points;
}

namespace Ui {

MainWindow::MainWindow(QWidget* _parent) : QMainWindow(_parent), input() { 
	render = new Render(this);
	panel = new Panel(this);
	panel_dock = new QDockWidget();
	menubar = new QMenuBar();
	QMenu* menu = new QMenu("File", menubar);
	menubar->addMenu(menu);
	QAction* open_file = new QAction("&Open", menu);
	QAction* exit = new QAction("&Exit", menu);
	menu->addAction(open_file);
	menu->addSeparator();
	menu->addAction(exit);

	connect(open_file, SIGNAL(triggered()), this, SLOT(open_file()));

	panel_dock->setWidget(panel);

	addDockWidget(Qt::LeftDockWidgetArea, panel_dock);
	setMenuBar(menubar);
	calculate();
	setCentralWidget(render);
}

MainWindow::~MainWindow(void) { 
	delete render;
}

void MainWindow::points_visualization_changed(int value) {
	render->set_points_visualization(value);
}

void MainWindow::convex_hull_visualization_changed(int value) {
	render->set_convex_hull_visualization(value);
}

void MainWindow::viewport_changed(int value) {
	render->set_viewport_scale(value);
}


void MainWindow::open_file(void) {
	QString filename = QFileDialog::getOpenFileName(this,tr("Open File"), QDir::currentPath(),tr("Convex Hull 2d Files (*.ch2d)"));
	if(!filename.isEmpty())	{
		input = boost::shared_ptr<Tujchi::Input>(new Tujchi::Input(filename.toStdString()));
		calculate();
	}

}

void MainWindow::calculate(void) {
	if(input) {
		render->clear_points();
		render->clear_convex_hull();
		std::vector< std::vector<Tujchi::Vector> > points = input->parse();
		for(unsigned int i = 0;i < points.size(); i++) {
			Tujchi::Jarvis jarvis(points.at(i));
			std::vector<Tujchi::Vector> result =  jarvis.convex_hull();
			render->add_points(points.at(i));
			render->add_convex_hull(result);
		}
	}
}


}

